﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using MongoDB;
using MongoDB.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Quartz.Service
{
    public class QuartzService : IHostedService
    {
        private readonly IQuartzStartup _quartzStartup;
        private readonly IMongoDB _mongoDB;
        public QuartzService(IServiceScopeFactory scopeFactory)
        {
            using (var scope = scopeFactory.CreateScope())
            {
                _quartzStartup = scope.ServiceProvider.GetRequiredService<IQuartzStartup>();
                _mongoDB = scope.ServiceProvider.GetService<IMongoDB>();
            };
        }
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            await _quartzStartup.Start(cancellationToken);
            var TaskManages = _mongoDB.GetCollection<Mongo_TaskManageModel>("Task_Manage").FindList(m => m.IsOpen == 1);
            if (TaskManages != null && TaskManages.Count > 0)
            {
                TaskManages.ForEach(m => _quartzStartup.AddJob(m));
            }
        }

        public async Task StopAsync(CancellationToken cancellationToken)
        {
            await _quartzStartup.Clear();
        }
    }
}
